﻿using EFCore.BulkExtensions;
using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using iWare.Wms.Core;
using iWare.Wms.Core.ExcelHelper;
using Mapster;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.UserModel;
using System.Data;

namespace iWare.Wms.Application
{
    /// <summary>
    /// 加急件管理服务
    /// </summary>
    [Route("api/UrgentItem")]
    [ApiDescriptionSettings("供应商模块", Name = "UrgentItem", Order = 100)]

    public class UrgentItemService : IDynamicApiController, ITransient
    {
        private readonly IRepository<WareMaterial, MasterDbContextLocator> _wareMaterialRep; //物料仓储
        private readonly ERPService _erpService; //ERP服务

        #region 默认
        /// <summary>
        /// 默认
        /// </summary>
        /// <param name="wareMaterialRep"></param>
        /// <param name="erpService"></param>
        public UrgentItemService(
            IRepository<WareMaterial, MasterDbContextLocator> wareMaterialRep,
            ERPService erpService
        )
        {
            _wareMaterialRep = wareMaterialRep;
            _erpService = erpService;
        }
        #endregion

        /// <summary>
        /// 分页查询供应商加急件物料
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("Page")]
        public async Task<PageResult<UrgentItemOutput>> Page([FromQuery] PurchaseUrgentItemInput input)
        {
            var account = CurrentUserInfo.Account;

            var list = await _wareMaterialRep.DetachedEntities
                    .Where(u => u.SupplerCode == account)
                    .Where(z => z.IsJiaJi == YesOrNot.Y)
                    .OrderByDescending(t => t.CreatedTime)
                    .ProjectToType<UrgentItemOutput>()
                    .ToADPagedListAsync(input.PageNo, input.PageSize);

            var xuHao = 0; //定义序号
            foreach (var item in list.Rows)
            {
                xuHao = xuHao + 1;
                item.XuHao = xuHao.ToString("0000");
            }

            return list;
        }

        /// <summary>
        /// 新建加急件物料
        /// </summary>
        [HttpPost("Add")]
        public async Task Add([FromBody] AddUrgentItemInput input)
        {
            var account = CurrentUserInfo.Account;

            var isExist = await _wareMaterialRep.DetachedEntities
                .AnyAsync(u => u.Code == input.Code && u.SupplerCode == account && u.IsJiaJi == YesOrNot.Y);
            if (isExist) throw Oops.Oh("数据已存在");

            var wareMaterial = input.Adapt<WareMaterial>();
            wareMaterial.IsJiaJi = YesOrNot.Y;
            wareMaterial.SupplerCode = account;
            //wareMaterial.InspectionMethod= _erpService.erpService
            await _wareMaterialRep.InsertAsync(wareMaterial);
        }

        /// <summary>
        /// 删除加急件物料
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("Delete")]
        public async Task Delete([FromBody] DeleteWareMaterialInput input)
        {
            var account = CurrentUserInfo.Account;

            int length = input.Id.Count;
            for (int i = 0; i < length; i++)
            {
                long Id = input.Id[i];
                var wareMaterial = await _wareMaterialRep
                    .FirstOrDefaultAsync(u => u.Id == Id && u.SupplerCode == account && u.IsJiaJi == YesOrNot.Y);
                await _wareMaterialRep.DeleteAsync(wareMaterial);
            }
        }

        /// <summary>
        /// 更新加急件物料
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("Edit")]
        public async Task Update([FromBody] UpdateWareMaterialInput input)
        {
            var account = CurrentUserInfo.Account;

            var isExist = await _wareMaterialRep.AnyAsync(u => u.Id == input.Id && u.SupplerCode == account
            && u.IsJiaJi == YesOrNot.Y, false);
            if (!isExist) throw Oops.Oh("数据不存在");

            var wareMaterial = input.Adapt<WareMaterial>();
            wareMaterial.SupplerCode = account;
            wareMaterial.IsJiaJi = YesOrNot.Y;
            await _wareMaterialRep.UpdateAsync(wareMaterial, ignoreNullValues: true);
        }

        /// <summary>
        /// 导入加急件物料信息
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("Import")]
        public async Task Import(IFormFile file)
        {
            await ToDataTable(file);
        }

        /// <summary>
        /// 上传文件转DT
        /// </summary>
        /// <param name="file"></param>
        /// <param name="hasTitle"></param>
        /// <returns></returns>
        [NonAction]
        public async Task ToDataTable(IFormFile file, bool hasTitle = true)
        {
            if (file == null || file.Length == 0) throw Oops.Oh("请选择导入文件");
            ExcelHelper.CheckIsExcel(file.FileName);
            IWorkbook workBook = WorkbookFactory.Create(file.OpenReadStream(), ImportOption.All);

            ISheet sheet = workBook.GetSheetAt(0);

            DataTable dt = null;
            if (hasTitle)
            {
                dt = ExcelHelper.SheetToDataTableHasTitle(sheet);

                var materialList = new List<WareMaterial>();
                foreach (DataRow item in dt.Rows)
                {
                    var isExist = await _wareMaterialRep.AnyAsync(u => u.Code == item["品名"].ToString() && u.SpecificationModel == item["规格"].ToString()
                     && u.SupplerCode == CurrentUserInfo.Account && u.IsJiaJi == YesOrNot.Y, false);
                    if (!isExist)
                    {
                        var inspectionMethod = InspectionMethodEnum.mianjian;

                        if (item["检验方式"].ToString() == "免检")
                            inspectionMethod = InspectionMethodEnum.mianjian;
                        else if (item["检验方式"].ToString() == "全检")
                            inspectionMethod = InspectionMethodEnum.quanjian;
                        else if (item["检验方式"].ToString() == "抽检(减量)")
                            inspectionMethod = InspectionMethodEnum.choujian_jianliang;
                        else if (item["检验方式"].ToString() == "抽检(正常)")
                            inspectionMethod = InspectionMethodEnum.choujian_zhengchang;
                        else if (item["检验方式"].ToString() == "抽检(加严)")
                            inspectionMethod = InspectionMethodEnum.choujian_jiayan;

                        var materialModel = new WareMaterial
                        {
                            Name = item["品名"].ToString(),
                            Code = item["品号"].ToString(),
                            SpecificationModel = item["规格"].ToString(),
                            Unit = item["单位"].ToString(),
                            InspectionMethod = inspectionMethod,
                            SupplerCode = CurrentUserInfo.Account,
                            IsJiaJi = YesOrNot.Y,
                            CreatedUserId = CurrentUserInfo.UserId,
                            CreatedUserName = CurrentUserInfo.Name,
                            CreatedTime = DateTimeOffset.Now,
                            UpdatedUserId = CurrentUserInfo.UserId,
                            UpdatedUserName = CurrentUserInfo.Name,
                            UpdatedTime = DateTimeOffset.Now,
                        };
                        materialList.Add(materialModel);
                    }
                }

                // 批量插入
                await _wareMaterialRep.Context.BulkInsertAsync(materialList);
            }
            else
            {
                dt = ExcelHelper.SheetToDataTable(sheet);
            }

            workBook.Close();
        }
    }
}
